package com.fanghuaiming.test.aio;

import static com.fanghuaiming.netty.utils.ByteBufferUtil.debugRead;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import lombok.extern.slf4j.Slf4j;

/****
 * @description: 异步文件IO
 * @version:1.0.0
 * @author fanghuaiming
 * @data Created in 2021/9/25 下午8:36
 *
 */
@Slf4j
public class FileAio {

  public static void main(String[] args) throws IOException {
      try {
          //获取文件异步channel
          AsynchronousFileChannel afc = AsynchronousFileChannel.open(Paths.get("1.txt"), StandardOpenOption.READ);
          ByteBuffer buffer = ByteBuffer.allocate(2);
          log.info("begin");
          //读取数据且设置回调 attachment:如果一次没读完则使用附件继续读
          afc.read(buffer, 0, null, new CompletionHandler<Integer, ByteBuffer>() {
              @Override
              public void completed(Integer result, ByteBuffer attachment) {
                log.info("读取完成个数:{}",result);
                buffer.flip();
                debugRead(buffer);
                buffer.clear();
              }

              @Override
              public void failed(Throwable exc, ByteBuffer attachment) {
                log.info("文件读取错误");
              }
          });
      } catch (IOException e) {
          e.printStackTrace();
      }
      log.info("主程序已经完成....");
      //为了保证守护线程
      System.in.read();
  }
}
